import isInt from "validator/lib/isInt";
import isFloat from "validator/lib/isFloat";
import isISBN from "validator/lib/isISBN";
import isLength from "validator/lib/isLength";
import isNumeric from "validator/lib/isNumeric";
import isMobilePhone from "validator/lib/isMobilePhone";
import isIdentityCard from "validator/lib/isIdentityCard";

function validate(data: Base.IObjectAny, rules: Base.IObjectAny): any[] {
  let validateResult = [];
  for (const key in data) {
    const obj = { name: "", status: false, message: "" };
    if (rules[key]) {
      const isNullish = data[key] ?? "nullish";
      if (rules[key].required || (data[key] + "" && isNullish !== "nullish")) {
        switch (rules[key].type) {
          case "int": {
            obj.name = key;
            obj.status = isInt(data[key] + "", { min: rules[key].min });
            if (!obj.status) obj.message = rules[key].message;
            break;
          }
          case "float": {
            obj.name = key;
            obj.status = isFloat(data[key] + "", { min: rules[key].min });
            if (!obj.status) obj.message = rules[key].message;
            break;
          }
          case "isbn": {
            obj.name = key;
            obj.status = isISBN(data[key] + "");
            if (!obj.status) obj.message = rules[key].message;
            break;
          }
          case "mobilePhone": {
            obj.name = key;
            obj.status = isMobilePhone(data[key] + "", ["zh-CN"]);
            if (!obj.status) obj.message = rules[key].message;
            break;
          }
          case "identityCard": {
            obj.name = key;
            obj.status = isIdentityCard(data[key] + "", ["zh-CN"] as any);
            if (!obj.status) obj.message = rules[key].message;
            break;
          }
          case "string": {
            obj.name = key;
            obj.status = isLength(data[key] + "", { min: rules[key].min });
            if (!obj.status) obj.message = rules[key].message;
            break;
          }
          case "numeric": {
            obj.name = key;
            obj.status = isNumeric(data[key] + "", { no_symbols: rules[key].noSymbols });
            if (!obj.status) obj.message = rules[key].message;
            break;
          }
        }
        validateResult.push(obj);
      }
    }
  }
  return validateResult;
}

export { validate };
